__author__ = 'vladbranzei'

from cherrypy import HTTPError
from pymongo.errors import DuplicateKeyError
from configs import configs as conf

class Leaderboard(object):

    id=game=name=type=order=creation_time=None

    def __init__(self, i_id, i_game, i_name, i_type, i_order, i_creation_time):
        self.id = i_id
        self.game = i_game
        self.name = i_name
        self.type = i_type
        self.order = i_order
        self.creation_time = i_creation_time


class LeaderboardMapper(object):
    def __init__(self):
        self.foundLeaderboard = None
        self.client = conf.client

    def check(self, i_game, i_name):
        query = {}
        query['game'] = i_game
        query['name'] = i_name

        try:
            leaderboards = self.client.ulise.leaderboards.find(query)
            count = leaderboards.count()
            if count == 1:
                leaderboard = leaderboards[0]
                self.foundLeaderboard = Leaderboard(i_id = str(leaderboard["_id"]), i_game=leaderboard["game"], i_name=leaderboard["name"], i_type=leaderboard["type"], i_order= leaderboard['order'], i_creation_time=leaderboard['creation_time'])
                return True
            else:
                return False

        except Exception as e:
            raise HTTPError(503)


    def create(self, i_game, i_name, i_type, i_order, i_creation_time):
        query = {}
        query['game'] = i_game
        query['name'] = i_name
        query['order'] = i_order
        query['type'] = i_type
        query['creation_time'] = i_creation_time

        try:
            result = self.client.ulise.leaderboards.insert(query)
            if result:
                self.foundLeaderboard = Leaderboard(i_id = str(result), i_game=i_game, i_name=i_name, i_type=i_type, i_order= i_order, i_creation_time=i_creation_time)
                return True
            else:
                return False
        except DuplicateKeyError as e:
            raise HTTPError(503)
        except Exception as e:
            raise HTTPError(503)










